# -*- coding: utf-8 -*-
import json
import logging
import os
from random import sample
from string import ascii_letters, digits
import time
import uuid

from wechatpayv3 import WeChatPay, WeChatPayType

# 微信支付商户号（直连模式）或服务商商户号（服务商模式，即sp_mchid)
MCHID = '1680751724'

# 商户证书私钥
with open('application/apps/cert/kg_apiclient_key.pem') as f:
    PRIVATE_KEY = f.read()

# 商户证书序列号
CERT_SERIAL_NO = '2D7E875B491709DF339566875F784040A1E04622'

# API v3密钥， https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_2.shtml
APIV3_KEY = 'Kangjin1234567891478523697896541'

# APPID，应用ID或服务商模式下的sp_appid
APPID = 'wx499a94f9d35b7545'

# 回调地址，也可以在调用接口的时候覆盖
NOTIFY_URL = 'https://127.0.0.1:8000/api/wx_notify'

# 微信支付平台证书缓存目录，减少证书下载调用次数，首次使用确保此目录为空目录。
# 初始调试时可不设置，调试通过后再设置，示例值:'./cert'。
# 新申请的微信支付商户号如果使用平台公钥模式，可以不用设置此参数。
CERT_DIR = None

# 日志记录器，记录web请求和回调细节
logging.basicConfig(filename=os.path.join(os.getcwd(), 'demo.log'), level=logging.DEBUG, filemode='a', format='%(asctime)s - %(process)s - %(levelname)s: %(message)s')
LOGGER = logging.getLogger("demo")

# 接入模式:False=直连商户模式，True=服务商模式
PARTNER_MODE = False

# 代理设置，None或者{"https": "http://10.10.1.10:1080"}，详细格式参见https://requests.readthedocs.io/en/latest/user/advanced/#proxies
PROXY = None

# 请求超时时间配置
TIMEOUT = (10, 30) # 建立连接最大超时时间是10s，读取响应的最大超时时间是30s

# 初始化
wxpay = WeChatPay(
    wechatpay_type=WeChatPayType.NATIVE,
    mchid=MCHID,
    private_key=PRIVATE_KEY,
    cert_serial_no=CERT_SERIAL_NO,
    apiv3_key=APIV3_KEY,
    appid=APPID,
    notify_url=NOTIFY_URL,
    cert_dir=CERT_DIR,
    logger=LOGGER,
    partner_mode=PARTNER_MODE,
    proxy=PROXY,
    timeout=TIMEOUT)


def pay_miniprog():
    # 以小程序下单为例，下单成功后，将prepay_id和其他必须的参数组合传递给小程序的wx.requestPayment接口唤起支付
    out_trade_no = ''.join(sample(ascii_letters + digits, 8))
    description = 'demo-description'
    amount = 1
    payer = {'openid': 'oogzA68lRguok77ku-GCthpmqybM'}
    code, message = wxpay.pay(
        description=description,
        out_trade_no=out_trade_no,
        amount={'total': amount},
        pay_type=WeChatPayType.MINIPROG,
        payer=payer
    )
    result = json.loads(message)
    if code in range(200, 300):
        prepay_id = result.get('prepay_id')
        timestamp = str(int(time.time()))
        noncestr = str(uuid.uuid4()).replace('-', '')
        package = 'prepay_id=' + prepay_id
        sign = wxpay.sign(data=[APPID, timestamp, noncestr, package])
        signtype = 'RSA'
        # return jsonify({'code': 0, 'result': {
        #     'appId': APPID,
        #     'timeStamp': timestamp,
        #     'nonceStr': noncestr,
        #     'package': 'prepay_id=%s' % prepay_id,
        #     'signType': signtype,
        #     'paySign': sign
        # }})
        print(prepay_id, timestamp, noncestr, package, signtype, sign)
    else:
        # return jsonify({'code': -1, 'result': {'reason': result.get('code')}})
        print('fail', result.get('code'))


if __name__ == '__main__':
    pay_miniprog()